package api

import (
	"cashback/cashback"
	"cashback/cashback/db"
	"cashback/middleware"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

type RebateResponse struct {
	PhoneNumber         string  `json:"phone_number"`
	ShareCashback       float64 `json:"share_cashback"`       // 分享返现金额
	InstallmentCashback float64 `json:"installment_cashback"` // 分期返现总金额
	DailyCashback       float64 `json:"daily_cashback"`       // 每日返现金额
	TotalCashback       float64 `json:"total_cashback"`       // 总返现金额
	Success             bool    `json:"success"`
	Message             string  `json:"message,omitempty"` //注释
}

// SetupRoutes 设置所有API路由
func SetupRoutes(r *gin.Engine) {
	r.POST("/api/cashback", middleware.AuthMiddleware(), ProcessCashbackHandler)
}

// ProcessCashbackHandler 处理返现计算的请求
func ProcessCashbackHandler(c *gin.Context) {
	// 1. 从token中获取电话号码（中间件已经解析好了）
	phoneNumber, exists := c.Get("phone_number")
	if !exists {
		c.JSON(http.StatusUnauthorized, RebateResponse{
			Success: false,
			Message: "未找到用户信息",
		})
		return
	}

	// 2. 从数据库查询用户信息
	user, err := db.GetUserByPhone(phoneNumber.(string))
	if err != nil {
		c.JSON(http.StatusNotFound, RebateResponse{
			Success: false,
			Message: "用户不存在",
		})
		return
	}

	// 3. 创建返现计算实例
	cashbackCalculator := cashback.NewUserCashback(user.ID)

	// 4. 从数据库获取用户信息
	/* eg该代码所需数据
	INSERT INTO users (
	phone_number,
	total_amount,
	monthly_fee,
	total_months,
	has_renewal,
	current_year,
	order_date
	) VALUES (
	'13800138000',    -- 电话号码
	50000.00,         -- 总金额
	1000.00,          -- 月费
	60,               -- 总月数（5年）
	false,            -- 是否续约
	'2024-01-01'      -- 订单时间
	);
	*/

	// 计算当前年份
	currentYear := calculateCurrentYear(user.OrderDate)
	cashbackCalculator.InstallmentInfo.CurrentYear = currentYear

	// 5. 分别计算返现
	shareCashback := cashbackCalculator.CalculateShareCashback()
	installmentCashback := cashbackCalculator.CalculateInstallmentCashback()

	// 计算每日分期返现金额
	dailyCashback := cashback.CalculateDailyCashback(installmentCashback, user.OrderDate)

	// 总返现 = 分享返现 + 分期返现
	totalCashback := shareCashback + installmentCashback

	// 6. 返回结果给前端
	c.JSON(http.StatusOK, RebateResponse{
		PhoneNumber:         phoneNumber.(string),
		ShareCashback:       shareCashback,
		InstallmentCashback: installmentCashback, // 分期返现总额
		DailyCashback:       dailyCashback,       // 每日分期返现金额
		TotalCashback:       totalCashback,
		Success:             true,
	})
}

// calculateCurrentYear 根据订单时间计算当前处于第几年
func calculateCurrentYear(orderDate time.Time) int {
	now := time.Now()
	yearDiff := now.Sub(orderDate).Hours() / (24 * 365)
	currentYear := int(yearDiff) + 1 // 加1是因为第一年从1开始计算

	// 确保年份在1-5年之间
	if currentYear < 1 {
		return 1
	}
	if currentYear > 5 {
		return 5
	}
	return currentYear
}
